//
//  BRRuleViewController.m
//  BrezzeSaaS
//
//  Created by IOS on 2021/11/17.
//  Copyright © 2021 Brezze GWG. All rights reserved.
//

#import "BRRuleViewController.h"
#import "BRPaymentViewController.h"
#import "BRRentingViewController.h"
#import "BRRentPreView.h"
#import "GXJWebViewController.h"
//#import "COWebPayVC.h"

#import "BRRentPreViewCard.h"
#import "BRAddCardViewController.h"
#import "BRWalletModel.h"

#import "BRPaymentDetailView.h"
#import "standard-Swift.h"

@interface BRRuleViewController ()

@property (nonatomic,strong) QMUILabel *textPlan;

@property (nonatomic,strong) QMUILabel *textTC;

@property (nonatomic,strong) QMUILabel *priceLab;


@property (nonatomic,strong) QMUIButton *agreeBtn;
@property (nonatomic,strong) QMUIButton *payBtn;

@property (nonatomic,strong) BRRulesTCView *ruleView;

@property (nonatomic,strong) BRRentPreView *payView;

@property (nonatomic,strong) BRRentPreViewCard *payViewCard;


@property (nonatomic,strong) UIButton *policyBtn;

@property (nonatomic,strong) BRPreRentModel *preDto;

//后续新增
@property (nonatomic,strong) BRWalletModel *walletModel;
@property (nonatomic,strong) BRCardModel *cardModel;

@property (nonatomic,strong) BRPaymentDetailView *addCardView;


@end

@implementation BRRuleViewController

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self  requestWallet];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self setUI];

    
}


#pragma mark - Request --
- (void)requestWallet {
    
    [BRUserManager getWallet:^(NSDictionary * _Nonnull dataDict, NSInteger respCode) {
//        self.tableView.hidden = NO;
        self.walletModel = [BRWalletModel mj_objectWithKeyValues:dataDict[@"data"]];
//        [self.tableView reloadData];
        
        if (self.walletModel.cardList.count > 0) {
            self.cardModel = self.walletModel.cardList[0];
            [self.payView changeVSCardHeight];
            self.payView.cardModel = self.cardModel;
            self.payViewCard.cardModel = self.cardModel;
        }
        
       
//
//        [self hiddAddBtn];
        
    } failed:^(NSInteger code, NSString * _Nonnull errMsg) {
//        self.tableView.hidden = NO;
    }];
}


#pragma mark --确认租借
- (void)req_rentCheck {
    
//    [self.payViewCard showSelf];
//        return;
    
    
    NSMutableDictionary *dic = [[NSMutableDictionary alloc] init];
    dic[@"scanUrl"] = self.sno;
    dic[@"source"] = @"1";
    dic[@"paymentChannel"] = @"stripe";
//    dic[@"rentType"] = @""; //"租借类型：1.卡预授权 2.预授权谷歌支付 3.预授权苹果支付

//    dic[@"id"] = @"0";
    [BRHud showInView:self.view];
    [[BRRequestManager shared] POST:[BRAPI preRent] params:dic succeed:^(NSDictionary * _Nonnull dataDict, NSInteger respCode) {

//        NSDictionary *dict = dataDict[@"data"];
//        NSString *resp = dict[@"resp"];
        self.preDto = [BRPreRentModel mj_objectWithKeyValues:dataDict[@"data"]];
        
        NSLog(@"dataDict1==%@",dataDict);
      
        if (self.preDto.scene > 1) {
            //租借场景:1.预授权租借 2.已授权租借 3.白名单租借  4.押金？ 5.预付款租借
            BROrderDetailModel *order = [BROrderDetailModel mj_objectWithKeyValues:self.preDto.order];
            [self rentSucc:order.orderNo];
            
            return;
        }
        [BRHud hiddenInView:self.view];
        

//        self.payView.depositPreAmount = self.preDto.prepaymentAmount;
        
//        self.payView.prepaymentAmount =   self.dto.preAuthAmount;
//        [self.payView showSelf];
        
        self.payView.prepaymentAmount = self.preDto.prepaymentAmount;
        
        
        NSString *defaultKey = [[NSUserDefaults standardUserDefaults] objectForKey:RecentlyusedcardKey];
        
        NSLog(@"RecentlyusedcardKey =====%@",defaultKey);
//        RecentlyusedcardKey
        if ([defaultKey isEqualToString:@"RecentlyusedcardKey"]&&self.cardModel) {
            [self.payViewCard showSelf];
        }else {
            [self.payView showSelf];
        }
        
        [self.payView ShowRecently:self.cardModel];

    } failed:^(NSInteger code, NSString * _Nonnull errMsg) {
        [BRHud hiddenInView:self.view];
    }];
    
}


- (void)req_rentCheck2 {

    
    
    NSMutableDictionary *dic = [[NSMutableDictionary alloc] init];
    dic[@"scanUrl"] = self.sno;
    dic[@"source"] = @"1";
    dic[@"paymentChannel"] = @"stripe";
//    dic[@"rentType"] = @""; //"租借类型：1.卡预授权 2.预授权谷歌支付 3.预授权苹果支付

//    dic[@"id"] = @"0";
    [BRHud showInView:self.view];
    [[BRRequestManager shared] POST:[BRAPI preRent] params:dic succeed:^(NSDictionary * _Nonnull dataDict, NSInteger respCode) {

//        NSDictionary *dict = dataDict[@"data"];
//        NSString *resp = dict[@"resp"];
        self.preDto = [BRPreRentModel mj_objectWithKeyValues:dataDict[@"data"]];
        
        NSLog(@"req_rentCheck2 ==%@",dataDict);
      
        if (self.preDto.scene > 1) {
            //租借场景:1.预授权租借 2.已授权租借 3.白名单租借  4.押金？ 5.预付款租借
            BROrderDetailModel *order = [BROrderDetailModel mj_objectWithKeyValues:self.preDto.order];
            [self rentSucc:order.orderNo];
            
            return;
        }else{
            
            
        }
        [BRHud hiddenInView:self.view];
        

        self.payView.depositPreAmount = self.preDto.depositAmount;
        
//        self.payView.prepaymentAmount =   self.dto.preAuthAmount;


    } failed:^(NSInteger code, NSString * _Nonnull errMsg) {
        [BRHud hiddenInView:self.view];
    }];
    
}



#pragma mark  //预授权判断 -之前绑定过卡的情况
 
- (void)req_rent:(NSString *)rentType {

    NSMutableDictionary *dic = [[NSMutableDictionary alloc] init];
    dic[@"scanUrl"] = self.sno;
    dic[@"source"] = @"1";
    dic[@"rentType"] = rentType; //"租借类型：1.卡预授权 2.预授权谷歌支付 3.预授权苹果支付
    
    dic[@"paymentChannel"] = @"stripe";

//    dic[@"type"] = @(BRPAY_PREAUTI); //支付类型
    dic[@"scene"] = @"1";  //租借场景：1.预授权租借 2.已授权租借 3.白名单租借 4.已交押金租借
    dic[@"customerId"] = self.cardModel.customerId;
    dic[@"bankcardId"] = self.cardModel.cardId;
    dic[@"cardToken"] = self.cardModel.bankToken;


    
    [BRHud showInView:self.view];
    
    //1:先判断授权是否有资格
    [[BRRequestManager shared] POST:[BRAPI preRent] params:dic succeed:^(NSDictionary * _Nonnull dataDict, NSInteger respCode) {

        BRPreRentModel *model = [BRPreRentModel mj_objectWithKeyValues:dataDict[@"data"]];
       
        BROrderDetailModel *dto = [BROrderDetailModel mj_objectWithKeyValues:model.order];

        NSLog(@"dataDict33%@",dataDict);
        
        
        if (model.resp.status == 11) {
            [self rentSucc:dto.orderNo];
            return;
        }
//        NSInteger scene = [dict[@"scene"] integerValue];
        if (model.resp!=nil) {
            
            if ([model.resp.displayMode isEqualToString:@"app"]&&model.resp.displayContent.length >0) {
         
                //租借场景:1.预授权租借 2.已授权租借 3.白名单租借
                NSLog(@"预授权成功--111");
                [[NSUserDefaults standardUserDefaults] setObject:@"RecentlyusedcardKey" forKey:RecentlyusedcardKey];

                 [[NSUserDefaults standardUserDefaults] synchronize];
                
                //2:先支付是否成功
//                model.clientSecret
                [[BRPayManager share] pre_toConfirmStPay:model.resp.displayContent succ:^(NSString *stripeId) {
                    
                    [BRHud hiddenInView:self.view];
                    NSLog(@"预授权成功--222");
    //                [self payStatus:BRPAY_SUCC by:model];
                    [self rentSucc:dto.orderNo];
                    
                } fail:^(NSString *errMsg, NSInteger code) {
                    [BRHud hiddenInView:self.view];
                    
                    [BRHud showAuto:[NSString stringWithFormat:@"ST-%@(%ld)",errMsg,code]];
                }];
                

                
                return;
                
            }
            
        }else if (model.success ==  2){
            
            NSLog(@"预授权成功-2：失败");
            [BRHud showAuto:Localized(@"失败")];
        }else if (model.success ==  3){
            
            NSLog(@"需要校验");
            
        }
        
        
        if (![rentType isEqualToString:@"1"]) {
            
            
            return;
        }
        
        if (BR_StringIsEmpty(model.resp.displayContent)) {
            [BRHud hiddenInView:self.view];
            
            [BRHud showAuto:Localized(@"home_failed")];
            
            return;
        }
        
//        COWebPayVC *vc = [[COWebPayVC alloc] init];
//        vc.url = model.resp.displayContent;
//        vc.modalPresentationStyle = UIModalPresentationFullScreen;
//        [self presentViewController:vc animated:YES completion:^{
//            
//        }];
//        WS(weakSelf);
//        vc.paySucc = ^(NSInteger state) {
//            
//            [BRHud hiddenInView:weakSelf.view];
//            
//            if (state == 1) {
//                
//                [weakSelf rentSucc:dto.orderNo];
//                
//            }else if (state == 2) {
//               
//                [BRHud showAuto:Localized(@"Public_cancel")];
//               
//                
//            } else {
//                
////                [BRHud showAuto:[NSString stringWithFormat:@"ePay-%@",Localized(@"swap_failed")]];
//                
//            }
//
//            
//        };

        

    } failed:^(NSInteger code, NSString * _Nonnull errMsg) {
        [BRHud hiddenInView:self.view];
    }];
}


- (void)req_applePay {
    
   

    
    if (![[BRPayManager share] isSupportApplePay]) {
        NSLog(@"添加app pay");
        [BRHud hiddenInView:self.view];

        BRCustiomAlertView *alertV = [[BRCustiomAlertView alloc] initWithTitle:Localized(@"public_notice") subTitle:Localized(@"payment_applePayAddMsg") cancelStr:Localized(@"public_notNow") succStr:Localized(@"public_confirm") cancelAction:^{

        } successAction:^{
            [BROpenURL openWallet];
        } showBC:YES];

        [self.view addSubview:alertV];

        return;
    }
    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
//    dic[@"paymentChannel"] = @"yabandpayPre";
    dic[@"paymentChannel"] = @"stripe";
    
    dic[@"scanUrl"] = self.sno;
    dic[@"source"] = @"1";
    dic[@"rentType"] = @"4"; //"租借类型：1.卡预授权 2.预授权谷歌支付
//    租借类型：1.Stripe绑定卡授权 2.Stripe输入卡授权 3.Stripe预授权谷歌支付 4.Stripe预授权苹果支付
    dic[@"scene"] = @"1";  //租借场景：1.预授权租借 2.已授权租借 3.白名单租借 4.已交押金租借
    
    dic[@"type"] = @(BRPAY_PREAUTI); //支付类型
    
    
//    dic[@"cabinetNo"] = self.sno;//机柜编号
    [BRPayManager share].dic = dic;
    
    
    
    [[NSUserDefaults standardUserDefaults] setObject:@"RecentlyusedcardKeyapple" forKey:RecentlyusedcardKey];

       [[NSUserDefaults standardUserDefaults] synchronize];
      
    

////    self.preDto.preAuthAmount
    [[BRPayManager share] applePay:self.preDto.preAuthAmount];
    
    //苹果支付回调
    WS(weakSelf);
    [BRPayManager share].applePrePayBlock = ^(NSString *orderNo) {
        
        
        [weakSelf rentSucc:orderNo];
        
    };
    
}


- (void)rentSucc:(NSString *)orderNo {
    
    [BRHud showAuto:Localized(@"rent_ejectTips") inView:self.view hideAfterDelay:2];
    WS(weakSelf);
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [UIView animateWithDuration:1.0 animations:^{
            self.view.alpha = 1.0;
        } completion:^(BOOL finished) {
            [weakSelf toRenting:orderNo];
        }];
    });
}

- (void)requestRent {
    
    [BRHud showInView:self.view];
    [[BRRequestManager shared] GET:[BRAPI rent:self.sno] params:nil succeed:^(NSDictionary * _Nonnull dataDict, NSInteger respCode) {

        
        [BRHud hiddenInView:self.view];
        
        NSString *orderNo = dataDict[@"data"][@"orderNo"];
        
        [self rentSucc:orderNo];
        
    } failed:^(NSInteger code, NSString * _Nonnull errMsg) {
        [BRHud hiddenInView:self.view];
    }];
}

- (void)toRenting:(NSString *)orderNo {
    BRRentingViewController *vc = [[BRRentingViewController alloc] init];
    vc.orderNo = orderNo;
    [self.navigationController pushViewController:vc animated:YES];
}


- (void)toConfirm {
    
    [self req_rentCheck];
    
//    [self requestRent];
    
//    if (self.agreeBtn.selected == NO) {
//        
//        [BRHud showAuto:Localized(@"toast_readDepositTermText")];
//        return;
//    }
    
//    if (self.dto.depositAmount.floatValue <= self.dto.paidDepositAmount.floatValue) {
//      // 预付款足够直接租借
//        [self requestRent];
//        
//        return;
//    }
//    
//    BRPaymentViewController *payVC = [BRPaymentViewController new];
//    payVC.amount = self.dto.depositAmount;
//    payVC.payType = BRPAY_Deposit;
//    [self.navigationController pushViewController:payVC animated:YES];
    
}
#pragma mark --预付款支付
- (void)br_toPayDeposit {
//    BRPaymentViewController *payVC = [BRPaymentViewController new];
//    payVC.amount = self.preDto.depositAmount;
////    payVC.payType = BRPAY_Deposit;
//    payVC.payType = BRPAY_PREAUTI;
//    payVC.paymentType = @"paymentType";
//    
//    payVC.isDepositScanIn = YES;
//    [self.navigationController pushViewController:payVC animated:YES];
//    
//    WS(weakSelf);
//    payVC.depositSuccBlock = ^{
//        NSLog(@"预授权支付回调11111");
////        [weakSelf toConfirm];
//        
//        
//        [BRHud showInView:self.view];
//        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//            [weakSelf req_rentCheck2];
//        });
//        
//        
//     
//        [weakSelf.payViewCard hiddenSelf];
//        [weakSelf.payView hiddenSelf];
//      
//     
//    };
}

#pragma mark // 使用卡支付-有卡的情况

-(void)br_cardPayClickBlock{
    
    [[NSUserDefaults standardUserDefaults] setObject:@"RecentlyusedcardKey" forKey:RecentlyusedcardKey];

     [[NSUserDefaults standardUserDefaults] synchronize];
    


    
    [self req_rent:@"1"];
}


- (void)clickPolicyBtn:(UIControl *)btn {
    _policyBtn.selected = !_policyBtn.selected;
    self.payBtn.enabled = _policyBtn.selected;
}

- (void)toPolicy {
//    depositPolicy  preAuthorizationPolicy
    NSString *url = [NSString stringWithFormat:@"%@?lang=%@",USERManager.termsOfUse,[BRLanguageManager share].language];
    NSString *titleStr = Localized(@"set_terms");
    GXJWebViewController *webView = [[GXJWebViewController alloc] init];
    webView.url = url ;
    [webView initWhiteBarWithTitle:titleStr isBack: YES];
    webView.modalPresentationStyle = UIModalPresentationFullScreen;
    [self presentViewController:webView animated:YES completion:nil];
}
    
#pragma mark --弹出
- (void)toCardPay {
   
    [[NSUserDefaults standardUserDefaults] setObject:@"RecentlyusedaddcardKey" forKey:RecentlyusedcardKey];

    [[NSUserDefaults standardUserDefaults] synchronize];
    
    [self.addCardView show];
    [self.addCardView br_becomeFirst];
    [self.view bringSubviewToFront:self.addCardView];
    [self.view bringSubviewToFront:self.view];
    
    [self.addCardView showPre:self.sno];
    

    WS(weakSelf);
    self.addCardView.toScan = ^{
        [weakSelf toScanCard];
    };
    
    self.addCardView.prePaySucc = ^(NSString *orderNo) {
//        [weakSelf resetName:shopName];
        [weakSelf rentSucc:orderNo];
        
        [[NSUserDefaults standardUserDefaults] setObject:@"RecentlyusedaddcardKey" forKey:RecentlyusedcardKey];

        [[NSUserDefaults standardUserDefaults] synchronize];
        
    };
}

- (void)toScanCard {
    
    WS(weakSelf);
    [[BRScanCardSwift shared] presentSheet:self succ:^(NSString * _Nonnull cardNum) {
        
        STPPaymentMethodCardParams *cardParam = [[STPPaymentMethodCardParams alloc] init];
        cardParam.number = cardNum;
        weakSelf.addCardView.paymentMethodCardParams = cardParam;
    } fail:^(NSString * _Nonnull failStr) {
        
        [BRHud showAuto:failStr inView:weakSelf.view];
    }];
}


- (void)setUI {
    
    
    [self br_createTop:@""];
    
    UIView *bottomV = [[UIView alloc] init];
    bottomV.backgroundColor = UIColor.whiteColor;
    [bottomV br_addBaseShadow];
    [self.view addSubview:bottomV];
    [bottomV mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.bottom.right.offset(0);
        make.height.mas_equalTo(200);
    }];
    
    NSString *btnTitle = Localized(@"home_toRent");
    
    QMUIButton *payBtn = [BRToolsView br_btnBGImg:btnTitle];
    _payBtn = payBtn;
    [bottomV addSubview:payBtn];
    [payBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo(52);
        make.width.mas_equalTo(kScreenWidth - 32);
        make.centerX.offset(0);
        make.bottom.offset(-(14 + kSafeAreaBottomHeight));
//        make.top.offset(14);
    }];
    [payBtn addTarget:self action:@selector(toConfirm) forControlEvents:UIControlEventTouchUpInside];
    // ---- xieyi0--
//    UIImage *sel = [[UIImage imageNamed:@"set_agree"] jk_imageScaledToSize:CGSizeMake(18, 18)];
//    UIButton *policyBtn = [UIButton buttonWithType:UIButtonTypeCustom];
//    [policyBtn setImage:[UIImage imageNamed:@"set_unagree"] forState:UIControlStateNormal];
//    [policyBtn setImage:sel forState:UIControlStateSelected];
//    [bottomV addSubview:policyBtn];
//    [policyBtn mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.width.height.mas_equalTo(16);
////        make.top.offset(16);
//        make.bottom.equalTo(policyBtn.mas_top).offset(-15);
//        make.left.offset(60);
//    }];
//    policyBtn.selected = YES;
//    policyBtn.userInteractionEnabled = NO;
//    _policyBtn = policyBtn;
//    
//    UIControl *btn = [[UIControl alloc] init];
//    [bottomV addSubview:btn];
//    [btn mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.centerX.equalTo(policyBtn);
//        make.width.height.mas_equalTo(50);
//        make.centerY.equalTo(policyBtn);
//    }];
//    [btn addTarget:self action:@selector(clickPolicyBtn:) forControlEvents:UIControlEventTouchUpInside];
    
    NSString* preAuthAmountStr = [BRPayManager br_amount:self.dto.preAuthAmount];
    
    QMUILabel *priceLab = [BRToolsView br_label:preAuthAmountStr textColor:UIColorMakeWithHex(@"#050101") font:[UIFont fontB:21]];
    priceLab.textAlignment = NSTextAlignmentRight;
    [bottomV addSubview:priceLab];
    _priceLab = priceLab;
    [priceLab mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.top.offset(20);
        make.width.mas_equalTo(kScreenWidth - 32);
        make.right.offset(-20);
        make.height.mas_greaterThanOrEqualTo(20);
    }];
    
    
    QMUILabel *preTitleLab = [BRToolsView br_label:Localized(@"wallet_preAuthorizationAmount") textColor:UIColorMakeWithHex(@"#050101") font:[UIFont fontS:17]];
    [bottomV addSubview:preTitleLab];
    [preTitleLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.offset(20);
        make.centerY.equalTo(priceLab.mas_centerY).offset(0);
    }];
    
    // ----------------
    
    YYLabel *agreeMsg = [YYLabel new];
    agreeMsg.font = [UIFont br_fontR:12];
    agreeMsg.numberOfLines = 0;
    agreeMsg.preferredMaxLayoutWidth = kScreenWidth - 40.;//100
    [bottomV addSubview:agreeMsg];
    [agreeMsg mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.offset(20);
        make.right.offset(-20);
        make.top.equalTo(priceLab.mas_bottom).offset(8);
//        make.height.mas_greaterThanOrEqualTo(25);
        make.bottom.equalTo(payBtn.mas_top).offset(-20);
    }];
    WS(weakSelf);
    NSString *terms = Localized(@"set_terms");
    NSString *agreeStr = [NSString stringWithFormat:Localized(@"scan_agreeTitle"),terms];
    NSMutableAttributedString *agreeAttStr = [[NSMutableAttributedString alloc] initWithString:agreeStr];
    [agreeMsg sizeToFit];
    NSRange rang = [agreeStr rangeOfString:terms];
    [agreeAttStr addAttribute:NSUnderlineStyleAttributeName value:[NSNumber numberWithInteger:NSUnderlineStyleSingle] range:rang ];
    agreeAttStr.yy_color = UIColorMakeWithHex(@"#646B80");
    agreeAttStr.yy_font = [UIFont br_fontR:12];
    [agreeAttStr yy_setTextHighlightRange:rang color:UIColorMakeWithHex(@"#646B80") backgroundColor:UIColor.clearColor tapAction:^(UIView * _Nonnull containerView, NSAttributedString * _Nonnull text, NSRange range, CGRect rect) {
        [weakSelf toPolicy];
        NSLog(@"0");
    }];
    agreeMsg.attributedText = agreeAttStr;

    
    [agreeMsg layoutIfNeeded];
    
    
    //------------------
    UIScrollView *sView = [[UIScrollView alloc] init];
    [self.view addSubview:sView];
    [sView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.offset(0);
        make.top.offset(kSafeAreaTopHeight);
        make.bottom.equalTo(bottomV.mas_top).offset(0);
    }];
    
    UIView *contView = [[UIView alloc] init];
    contView.backgroundColor = UIColor.clearColor;
    [sView addSubview:contView];
    [contView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.offset(0);
        make.width.offset(kScreenWidth);
    }];
    
    UIStackView *stackViewBig = [[UIStackView alloc] init];
    stackViewBig.axis = UILayoutConstraintAxisVertical;
    stackViewBig.alignment = UIStackViewAlignmentCenter;
    stackViewBig.spacing = 12;
    [contView addSubview:stackViewBig];
    [stackViewBig mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.mas_equalTo(kScreenWidth);
        make.left.right.offset(0);
        make.top.offset(28);
        make.bottom.offset(-10);
    }];
    //--------------stackView----
    UIStackView *stackView = [UIStackView new];
    CGFloat x_x = (kScreenWidth - 216) / 4.0;
    NSArray *titles = @[@"Lightning",@"Micro",@"Type-C"];
    for (int i = 0; i < titles.count; i++) {

        UIView *view = [[UIView alloc] initWithFrame:CGRectMake((x_x +  72) * i + x_x, 0, 72, 88)];
        view.backgroundColor = UIColorClear;
        NSString *imgstr  =  [NSString stringWithFormat:@"home_ic_type%d",i];
        UIImageView *img = [[UIImageView alloc] initWithImage:UIImageMake(imgstr)];
        [view addSubview:img];
        [img mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(view);
            make.width.mas_equalTo(52);
            make.height.mas_equalTo(52);
            make.centerX.offset(0);

        }];
        
        QMUILabel *depositL = [BRToolsView br_label:titles[i] textColor:kColorTitle38 font:[UIFont fontM:14]];
        depositL.textAlignment = NSTextAlignmentCenter;
        depositL.numberOfLines = 0;
        [view addSubview:depositL];
        [depositL mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.equalTo(view);
            make.top.equalTo(img.mas_bottom).offset(8);
            make.bottom.offset(-4);
        }];
        
        CGFloat view_x = (x_x +  72) * i + x_x;
        [stackView addSubview:view];
        [view mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.offset(0);
            make.width.mas_equalTo(72);
            make.height.mas_equalTo(88);
            make.left.offset(view_x);
            make.bottom.offset(0);
        }];

    }
    
    [stackViewBig addArrangedSubview:stackView];
    [stackView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.mas_equalTo(kScreenWidth);
    }];
    
    // 规则和station
    CGFloat view_w = kScreenWidth - 28;
    UIView *contentV = [UIView new];
    contentV.backgroundColor = UIColorClear;
    
    [stackViewBig addArrangedSubview:contentV];
    [contentV mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.mas_equalTo(view_w);
    }];
    //--------------rule----
    UIStackView *stackTitle = [[UIStackView alloc] init];
    stackTitle.axis = UILayoutConstraintAxisVertical;
    stackTitle.spacing = 28;
    [contentV addSubview:stackTitle];
    [stackTitle mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.offset(0);
        make.width.mas_equalTo(view_w);
        make.top.bottom.offset(0);
    }];
    
    UIView *ruleV = [[UIView alloc] init];
    ruleV.layer.cornerRadius = 24;
    ruleV.layer.masksToBounds = YES;
    ruleV.backgroundColor = UIColor.whiteColor;
    [stackTitle addArrangedSubview:ruleV];
//    [ruleV mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.left.offset(14);
//        make.right.offset(-14);
//        make.top.equalTo(stackView.mas_bottom).offset(14);
//        make.bottom.offset(-20);
//    }];
    
    UIStackView *stackRule = [[UIStackView alloc] init];
    stackRule.axis = UILayoutConstraintAxisVertical;
    stackRule.spacing = 20;
    [ruleV addSubview:stackRule];
    [stackRule mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.offset(20);
        make.top.offset(20);
        make.right.offset(-20);
        make.bottom.offset(-20);
    }];
    
    self.ruleView = [[BRRulesTCView alloc] init];
    
    
    self.ruleView.titleL.text = Localized(@"home_billingRules");
    self.ruleView.textTC.text = [[BRUserManager share] br_ruleOfModel:self.dto.billing];

//    if (self.dto.branchName.length == 0) {
//        [self.ruleView mas_makeConstraints:^(MASConstraintMaker *make) {
//            make.left.offset(20);
//            make.top.offset(20);
//            make.right.offset(-20);
//            make.bottom.offset(-20);
//        }];
//        return;
//    }
//    
//    [self.ruleView mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.left.offset(20);
//        make.top.offset(20);
//        make.right.offset(-20);
//    
//    }];

    UIView *stationV = [UIView new];
    stationV.layer.cornerRadius = 10;
    stationV.layer.masksToBounds = YES;
    stationV.backgroundColor = kColorBGF5;
    

    UIImageView *imgbG = [[UIImageView alloc] initWithImage:UIImageMake(@"home_mapSmall")];
    [stationV addSubview:imgbG];
    [imgbG mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.offset(0);
        make.left.offset(8);
        make.width.height.mas_equalTo(56);
    }];
    UIImageView *imgSub = [[UIImageView alloc] initWithImage:UIImage.qd_homeLocBigImg];
    [imgbG addSubview:imgSub];
    [imgSub mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.centerX.offset(0);
        make.width.height.mas_equalTo(40);
    }];

    QMUILabel *stationL = [BRToolsView br_label:self.dto.branchName textColor:kColorTitle font:[UIFont fontS:15]];
    stationL.numberOfLines = 2;
    [stationV addSubview:stationL];
    [stationL mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(imgbG.mas_centerY).offset(0);
        make.left.equalTo(imgbG.mas_right).offset(12);
        make.right.offset(-12);
    }];
    
    [self.view bringSubviewToFront:bottomV];
    
    [stackRule addArrangedSubview:self.ruleView];
    
    [stackRule addArrangedSubview:stationV];
    [stationV mas_makeConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo(72);
    }];
    stationV.hidden = self.dto.branchName.length == 0;
    
    // --------- pre rule ----
    UIView *preBG = [[UIView alloc] init];
    preBG.layer.cornerRadius = 20;
    preBG.layer.masksToBounds = YES;
    preBG.backgroundColor = UIColor.whiteColor;
    [stackTitle addArrangedSubview:preBG];
    
    QMUILabel *rulePreL = [BRToolsView br_label:Localized(@"wallet_preAuthorizationRule") textColor:UIColor.qd_titleTextColor font:[UIFont fontS:17]];
    [preBG addSubview:rulePreL];
    NSString *preMoney = [NSString stringWithFormat:Localized(@"wallet_frozeTips"),[BRPayManager br_amount:self.dto.preAuthAmount]];
    QMUILabel *rulePreSubL = [BRToolsView br_label:preMoney textColor:UIColor.qd_titleTextColor2 font:[UIFont fontR:14]];
    rulePreSubL.numberOfLines = 0;
    [preBG addSubview:rulePreSubL];
    
//    rulePreL.textAlignment = NSTextAlignmentCenter;
//    rulePreSubL.textAlignment = NSTextAlignmentCenter;
    
    [rulePreL mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.offset(20);
        make.right.offset(-20);
        make.top.offset(20);
    }];
    [rulePreSubL mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.offset(20);
        make.right.offset(-20);
        make.top.equalTo(rulePreL.mas_bottom).offset(8);
        make.bottom.offset(-20);
    }];
    
    //----------------
    [self.view addSubview:self.payView];
    [self.payView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.offset(0);
    }];
    
    
    [self.view addSubview:self.payViewCard];
    [self.payViewCard mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.offset(0);
    }];
    
    
    self.payViewCard.agreeMsgBlock = ^{
        [weakSelf.payViewCard hiddenSelf];
        [weakSelf.payView showSelf];
        
    };
    
    self.payView.depositPreAmount = self.dto.depositAmount;
    
    self.payView.toDepositBlock = ^{
        [weakSelf br_toPayDeposit];
    };
    

    self.payView.cardPayClickBlock = ^{
        [weakSelf br_cardPayClickBlock];
    };
    
    
    self.payViewCard.cardPayClickBlock = ^{
        [weakSelf br_cardPayClickBlock];
    };
    
    
    // 0 apple 1 yabandpay
//    weakSelf
    self.payView.prePayClickBlock = ^(NSInteger index) {
        
        if (index == 1) {

            
//            BRAddCardViewController *vc = [[BRAddCardViewController alloc] init];
//              [weakSelf.navigationController pushViewController:vc animated:YES];
//          
//            vc.editSuccBlock = ^(NSString *shopName) {
////                [weakSelf resetName:shopName];
//            };
            
//            [BRHud showInView:weakSelf.view];
//            
//            [BRHud hiddenInView:weakSelf.view];
            [weakSelf toCardPay];
            
            return;
        }
        [weakSelf req_applePay];
    };
    
    
    
    //让addview 早于底部按钮添加
    [self.view addSubview:self.addCardView];
}

- (BRRentPreView *)payView {
    
    if (_payView == nil) {
        _payView = [[BRRentPreView alloc] init];
    }
    return _payView;
}


- (BRRentPreViewCard *)payViewCard {
    
    if (_payViewCard == nil) {
        _payViewCard = [[BRRentPreViewCard alloc] init];
    }
    return _payViewCard;
}

- (BRPaymentDetailView *)addCardView {
    if (_addCardView == nil) {
        _addCardView = [[BRPaymentDetailView alloc] initAddViewWithFrame:self.view.bounds];
       
    }
    return _addCardView;
}


/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
